package com.xiaok.netty.server.channelInitializer;

import com.xiaok.common.protobuf.Message;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author xiaok
 * @create 2020--09-30 10:18
 */

@Component(value = "serverChannelInitializer")
public class ServerChannelInitializer extends ChannelInitializer<SocketChannel> {

    @Value("${server.reader_idle_time_seconds}")
    private Integer readerIdleTimeSeconds;
    @Value("${server.writer_idle_time_seconds}")
    private Integer writerIdleTimeSeconds;
    @Value("${server.all_idle_time_seconds}")
    private Integer allIdleTimeSeconds;

    @Autowired
    @Qualifier("serverHeartHandler")
    private ChannelInboundHandlerAdapter serverHeartHandler;
    @Autowired
    @Qualifier("otherServerHandler")
    private ChannelInboundHandlerAdapter otherServerHandler;


    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {


        ChannelPipeline pipeline = socketChannel.pipeline();
        //检测空闲必须放在这里 因为pipeline是分顺序加载的
        pipeline.addLast("idleStateHandler",new IdleStateHandler(readerIdleTimeSeconds,writerIdleTimeSeconds,allIdleTimeSeconds, TimeUnit.SECONDS));
        //解码器必须放在前面，否则发数据收不到
        pipeline.addLast(new ProtobufVarint32FrameDecoder());//添加protobuff解码器
        pipeline.addLast(new ProtobufDecoder(Message.MessageBase.getDefaultInstance()));//添加protobuff对应类解码器
        pipeline.addLast(new ProtobufVarint32LengthFieldPrepender());//protobuf的编码器 和上面对对应
        pipeline.addLast(new ProtobufEncoder());//protobuf的编码器
        //自定义的hanlder
        pipeline.addLast("serverHeartHandler", serverHeartHandler);
        pipeline.addLast("otherServerHandler", otherServerHandler);
    }
}
